package org.shangrila.bme.mb;

/**
 * BmeSupplier公用下拉数据服务---转换器
 */
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;

import org.shangrila.bme.eo.BmeSupplier;

@FacesConverter("bmeSupplierConverter")
public class BmeSupplierConverter implements Converter<Object> {

    public Object getAsObject(FacesContext fc, UIComponent uic, String value) {
    	//System.out.println("getAsObject="+value);
        if(value != null && value.trim().length() > 0) {
            try {            	
            	//这种查找MB的方式注意范围SessionScoped/ApplicationScopde，需要分别查找getSessionMap()/getApplicationMap()：
            	BmeCommEntityService service = (BmeCommEntityService) fc.getExternalContext().getApplicationMap().get("bmeCommEntityService");
            	
            	for(BmeSupplier bc:service.getBmeSuppliers()) {
            		if(bc.getId().equalsIgnoreCase(value)) {            			
            			return bc;
            		}
            	}
            	return null ;

            } catch(NumberFormatException e) {
                throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Conversion Error", "Not a valid object."));
            }
        }
        else {
            return null;
        }
    }
    
	//将模型的对象（BmeSupplier）值（selectedBmeSupplier），渲染为页面需要的String值（selectOneMenu显示）
    public String getAsString(FacesContext fc, UIComponent uic, Object object) {
    	//System.out.println("getAsString="+object);
        if(object != null) {        	
            return String.valueOf(((BmeSupplier) object).getId());
        }
        else {
            return null;
        }
    }
}